package com.guomei.controller;

import com.guomei.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api1/redis")
@Slf4j
public class RedisController {
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 测试普通键值对操作
     */
    @PostMapping("/set")
    public Map<String, Object> setKey(@RequestParam String key,
                                      @RequestParam String value,
                                      @RequestParam(required = false, defaultValue = "-1") long expire) {
        redisUtils.set(key, value, expire);
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "键值对设置成功");
        return result;
    }
    // 注入配置的Redis密码
    @Value("${spring.redis.password}")
    private String redisPassword;

    @GetMapping("/test/redis/password")
    public String getRedisPassword() {
        log.info("开始请求");
        // 访问该接口，查看返回的密码是否和配置一致（应为r-bp1joktxxix0t6x0ph:Taosiyu1104）
        return "Loaded Redis password: " + redisPassword;
    }
    /**
     * 获取普通键值
     */
    @GetMapping("/get")
    public Map<String, Object> getKey(@RequestParam String key) {
        Map<String, Object> result = new HashMap<>();

        try {
            Object value = redisUtils.get(key);

            if (value == null) {
                result.put("success", false);
                result.put("message", "键不存在或已过期");
            } else {
                result.put("success", true);
                result.put("message", "获取成功");
            }

            result.put("key", key);
            result.put("value", value);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取键值失败: " + e.getMessage());
            result.put("value", null);
            log.error("Redis获取键值失败，键名: {}", key, e);
        }

        return result;
    }

    /**
     * 测试删除键
     */
    @DeleteMapping("/delete")
    public Map<String, Object> deleteKey(@RequestParam String key) {
        boolean deleted = redisUtils.delete(key);
        Map<String, Object> result = new HashMap<>();
        result.put("success", deleted);
        result.put("message", deleted ? "键删除成功" : "键不存在或删除失败");
        return result;
    }
}
